<template>
  <el-dialog
    :title="formData.id ? '编辑部门' : '新增部门'"
    :visible="showDialog"
    @close="closeFn"
  >
    <el-form ref="form" :rules="rules" label-width="120px" :model="formData">
      <el-form-item label="角色名称" prop="name">
        <el-input v-model="formData.name" />
      </el-form-item>
      <el-form-item label="角色描述" prop="description">
        <el-input v-model="formData.description" />
      </el-form-item>
    </el-form>
    <template v-slot:footer>
      <el-row type="flex" justify="center">
        <el-button size="small" @click="closeFn">取 消</el-button>
        <el-button size="small" type="primary" @click="submit">确 定</el-button>
      </el-row>
    </template>
  </el-dialog>
</template>
<script>
import { addRole, getRoleDetail, editRole } from '@/api/setting'
export default {
  props: {
    showDialog: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      formData: {
        name: '',
        description: ''
      },
      rules: {
        name: [
          { required: true, message: '角色名称不能为空！', trigger: 'blur' },
          { min: 1, max: 10, message: '角色名称长度1到10位!', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '角色描述不能为空！', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 获取角色详情
    async getRoleDetail(id) {
      const res = await getRoleDetail(id)
      console.log(res)
      this.formData = res.data.data
    },
    submit() {
      this.$refs.form.validate(async bool => {
        if (bool) {
          if (this.formData.id) {
            // 编辑
            await editRole(this.formData)
          } else {
            // 新增
            await addRole(this.formData)
          }
          // 关闭弹窗
          this.closeFn()
          // 调用接口
          this.$emit('updateEvent')
        }
      })
    },
    closeFn() {
      this.$emit('update:showDialog', false)
      // 清空列表
      this.formData = {
        name: '', // 角色名称
        description: '' // 角色描述
      }
      // 清空校验规则
      this.$refs.form.resetFields()
    }
  }
}
</script>
<style>

</style>
